#!/usr/bin/env python
# -*- coding: UTF-8 -*-

try:
	import pygame
	import sys
	from animatable import Animatable
	from cursor import *
	from pygame.locals import *
	from utils import *
except ImportError, err:
	print "Could not load %s module." % (err)
	sys.exit(2)

'''
Battlefield

A simple and hopefully reusable object that loads the scenario map
and handles its own movement.

In the future, it might receive a two-dimensional array of map-tile
IDs and build the map from that.
'''

class Battlefield(pygame.sprite.Sprite, Animatable):
	def __init__(self, scenario, name):
		pygame.sprite.Sprite.__init__(self)
		Animatable.__init__(self)
		self.set_anim_params(FLD_TILE_SZ)

		self.scenario = scenario
		self.image = load_image('./data/maps/' + name)
		self.rect = self.image.get_rect()
		self.screen_rect = pygame.display.get_surface().get_rect()
		# how many pixels remain outside the screen when we are at
		# the bottom right corner of the map?
		self.right_overage = self.screen_rect.width % 48
		self.bottom_overage = self.screen_rect.height % 48

	def update(self):
		if self.moving:
			self.slide()
		self.rect.topleft = (self.x, self.y)

	def move(self, key):
		if (key == K_UP and self.rect.top < 0) \
		or (key == K_RIGHT \
			and (self.rect.right - self.screen_rect.width) > self.right_overage) \
		or (key == K_DOWN \
			and (self.rect.bottom - self.screen_rect.height) > self.bottom_overage) \
		or (key == K_LEFT and self.rect.left < 0):
			self.moving = key
			return key
		else:
			return 0

	def r_move(self, key):
		moved = self.move(key)
		if key == K_UP: self.moving = (moved and K_DOWN)
		elif key == K_RIGHT: self.moving = (moved and K_LEFT)
		elif key == K_DOWN: self.moving = (moved and K_UP)
		elif key == K_LEFT: self.moving = (moved and K_RIGHT)
		return self.moving

	def colorize(self, color, tilelist):
		# creates a coloured surface for layer 2
		self.overlay = pygame.sprite.Sprite()
		self.overlay.image = pygame.Surface(self.rect.size)
		self.overlay.rect = self.rect
		self.overlay.image.fill((255,0,0))
		self.overlay.image.set_alpha(96)

		self.scenario.layers[2].add(self.overlay)
